import { createIntl } from 'react-intl';

import enUS0 from 'antd/es/locale/en_US';
import zhCN0 from 'antd/es/locale/zh_CN';
import zhTW0 from 'antd/es/locale/zh_TW';

import lang_enUS0 from '@/locales/en-US';
import lang_zhCN0 from '@/locales/zh-CN';
import lang_zhTW0 from '@/locales/zh-TW';

export { createIntl };
export {
    FormattedDate,
    FormattedDateParts,
    FormattedDisplayName,
    FormattedList,
    FormattedMessage,
    FormattedNumber,
    FormattedNumberParts,
    FormattedPlural,
    FormattedRelativeTime,
    FormattedTime,
    FormattedTimeParts,
    IntlContext,
    IntlProvider,
    RawIntlProvider,
    createIntlCache,
    defineMessages,
    injectIntl,
    useIntl,
} from 'react-intl';

const useLocalStorage = true;

function flattenMessages(nestedMessages: Record<string, any>, prefix = '') {
    return Object.keys(nestedMessages).reduce((messages: Record<string, any>, key) => {
        const value = nestedMessages[key];
        const prefixedKey = prefix ? `${prefix}.${key}` : key;
        if (typeof value === 'string') {
            messages[prefixedKey] = value;
        } else {
            Object.assign(messages, flattenMessages(value, prefixedKey));
        }
        return messages;
    }, {});
}

export const localeInfo: { [key: string]: any } = {
    'en-US': {
        messages: {
            ...flattenMessages(lang_enUS0),
        },
        locale: 'en-US',
        antd: {
            ...enUS0,
        },
        momentLocale: 'en',
    },
    'zh-CN': {
        messages: {
            ...flattenMessages(lang_zhCN0),
        },
        locale: 'zh-CN',
        antd: {
            ...zhCN0,
        },
        momentLocale: 'zh-cn',
    },
    'zh-TW': {
        messages: {
            ...flattenMessages(lang_zhTW0),
        },
        locale: 'zh-TW',
        antd: {
            ...zhTW0,
        },
        momentLocale: 'zh-tw',
    },
};

/**
 * 获取当前选择的语言
 * @returns string
 */
export function getLocale() {
    // please clear localStorage if you change the baseSeparator config
    // because changing will break the app
    const lang =
        navigator.cookieEnabled && typeof localStorage !== 'undefined' && useLocalStorage
            ? window.localStorage.getItem('_locale')
            : '';
    // support baseNavigator, default true
    const isNavigatorLanguageValid = typeof navigator !== 'undefined' && typeof navigator.language === 'string';
    const browserLang = isNavigatorLanguageValid ? navigator.language.split('-').join('-') : '';
    return lang || browserLang || 'zh-CN';
}

/**
 * 获取当前的 intl 对象
 */
export function getIntl(locale?: string) {
    // 获取当前 locale
    let localeVal = locale;
    if (!localeVal) localeVal = getLocale();
    // 如果存在于 localeInfo 中
    if (localeVal && localeInfo[localeVal]) {
        return createIntl(localeInfo[localeVal]);
    }
    // 使用 zh-CN
    if (localeInfo['zh-CN']) {
        return createIntl(localeInfo['zh-CN']);
    }

    // 如果还没有，返回一个空的
    return createIntl({
        locale: 'zh-CN',
        messages: {},
    });
}

/**
 * 获取当前选择的方向
 * @returns string
 */
export function getDirection() {
    const lang = getLocale();
    // array with all prefixs for rtl langueges ex: ar-EG , he-IL
    const rtlLangs = ['he', 'ar', 'fa', 'ku'];
    const direction = rtlLangs.filter((lng) => lang.startsWith(lng)).length ? 'rtl' : 'ltr';
    return direction;
}

/**
 * 获取语言列表
 * @returns string[]
 */
export const getAllLocales = () => Object.keys(localeInfo);
